import 'package:objectbox/objectbox.dart';
import '../../../objectbox.g.dart';
import '../../bean.dart';
import '../basemodel.dart';

@Entity()
class FavoriteDApp {
  @Id()
  int id;
  String? uid;
  String? name;
  String? logo;
  String? url;
  String? description;
  String? chains;
  String? statement;

  FavoriteDApp(
      {this.id = 0,
      this.uid,
      this.name,
      this.logo,
      this.url,
      this.description,
      this.chains,
      this.statement});

  FavoriteDApp.fromDApp({this.id = 0, required DAppBean dApp}) {
    name = dApp.name;
    logo = dApp.logo;
    url = dApp.url;
    uid = dApp.uid!;
    description = dApp.description;
    statement = dApp.statement;
    chains = dApp.chains == null ? '' : dApp.chains!.join(',');
  }

  static DAppBean toDApp(FavoriteDApp dApp) {
    List<int> list;
    if (dApp.chains!.isNotEmpty) {
      list = dApp.chains!
          .split(',')
          .map((e) => int.parse(e))
          .toList(growable: false);
    } else {
      list = [];
    }
    DAppBean dAppBean = DAppBean(dApp.uid, dApp.name, dApp.logo, dApp.url,
        dApp.description, list, dApp.statement ?? '');

    return dAppBean;
  }
}

class FavoriteDAppModel extends BaseModel<FavoriteDApp> {
  FavoriteDAppModel(Box<FavoriteDApp> box) : super(box);

  List<DAppBean> getAllFavoriteDApp(String uid) {
    return box
        .query(FavoriteDApp_.uid.equals(uid))
        .build()
        .find()
        .map((e) => FavoriteDApp.toDApp(e))
        .toList(growable: false);
  }

  bool isFavorite(DAppBean dApp) {
    String url = dApp.url!;
    String uid = dApp.uid!;
    // String domain = Uri.parse(url).host;
    // return box
    //         .query(FavoriteDApp_.url
    //             .startsWith('http://$domain')
    //             .or(FavoriteDApp_.url.startsWith('https://$domain')))
    //         .build()
    //         .count() >
    //     0;
    return box
            .query((FavoriteDApp_.uid.equals(uid) &
                FavoriteDApp_.url.equals(url, caseSensitive: false)))
            .build()
            .count() >
        0;
  }

  bool addFavoriteDApp(DAppBean dApp) {
    if (isFavorite(dApp)) {
      return false;
    }
    return box.put(FavoriteDApp.fromDApp(dApp: dApp)) > 0;
  }

  bool removeFavoriteDApp(DAppBean dApp) {
    String url = dApp.url!;
    List<int> ids = box.query(FavoriteDApp_.url.equals(url)).build().findIds();
    if (ids.isNotEmpty) {
      return box.removeMany(ids) > 0;
    } else {
      return false;
    }
  }
}
